// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.UserControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService;
using Microsoft.Security.Application;
using System.Xml;
using System.IO;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;
namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks
{
    public partial class ViewTasks : System.Web.UI.Page
    {
        string strFieldsXml = @"";

        public void Page_Error(object sender, EventArgs e)
        {
            //throw new HttpException(500, "Unhandled Exception.");
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            //Only task admin, task manager and trusted task user has task user role in them.
            if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskUser")))
                throw new HttpException(403, "Requires Task User or Trusted Task User or Task Manager Role");

            if (ViewState["FieldsXml"] != null)
            {
                strFieldsXml = ViewState["FieldsXml"].ToString();
            }
            else
            {

                if (File.Exists(Server.MapPath(Utility.GetConfigurationValue("PathforTaskFilterXML"))))
                    strFieldsXml = File.ReadAllText(Server.MapPath(Utility.GetConfigurationValue("PathforTaskFilterXML")));
                TasksServiceClient tasks = new TasksServiceClient();
                List<TaskStatus> lstStatus = new List<TaskStatus>();
                lstStatus.AddRange(tasks.GetAllTaskStatus());
                List<Group> lstGroups = new List<Group>();
                lstGroups.AddRange(tasks.GetActiveGroups());
                List<Category> lstCategories = new List<Category>();
                lstCategories.AddRange(tasks.GetActiveCategories());
                List<User> lstUsers = new List<User>();
                //Only task manager and task admin has task manager.
                if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
                    lstUsers.AddRange(tasks.GetTasksUsers());
                else
                {
                    User usr = new User();
                    usr.ID = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;
                    usr.Name = ((CISF.Security.Principal.CISFIdentity)User.Identity).FullName;
                    usr.LoginName = User.Identity.Name;
                    lstUsers.Add(usr);
                }
                lstUsers.Sort(new TaskUserComparer());
                string strData ="";
                foreach (TaskStatus ts in lstStatus) 
                {
                    strData += @"<AllowedValue Key=""" + ts.ID.ToString() + @""">" + AntiXss.XmlEncode(ts.Name) + "</AllowedValue>" + Environment.NewLine;
                }
                strFieldsXml = strFieldsXml.Replace("{AllowedStatusValues}", strData);
                strData = "";
                foreach (Group g in lstGroups)
                {
                    strData += @"<AllowedValue Key=""" + g.ID.ToString() + @""">" + AntiXss.XmlEncode(g.Name) + "</AllowedValue>" + Environment.NewLine;
                }
                strFieldsXml = strFieldsXml.Replace("{AllowedGroupValues}", strData);
                strData = "";
                foreach (Category c in lstCategories)
                {
                    strData += @"<AllowedValue Key=""" + c.ID.ToString() + @""">" + AntiXss.XmlEncode(c.Name) + "</AllowedValue>" + Environment.NewLine;
                }
                strFieldsXml = strFieldsXml.Replace("{AllowedCategoryValues}", strData);
                strData = "";
                foreach (User u in lstUsers)
                {
                    if (u.ID == ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId)
                        strData += @"<AllowedValue Key=""" + u.ID.ToString() + @""" Default=""True"">" + AntiXss.XmlEncode(u.Name) + "</AllowedValue>" + Environment.NewLine;
                    else
                    strData += @"<AllowedValue Key=""" + u.ID.ToString() + @""">" + AntiXss.XmlEncode(u.Name) + "</AllowedValue>" + Environment.NewLine;
                }
                strFieldsXml = strFieldsXml.Replace("{AllowedUserValues}", strData);

                lstCategories = null;
                lstGroups = null;
                lstStatus = null;
                lstUsers = null;
                tasks.Close();

                //if (Request.QueryString["riskid"] != "")
                if (!string.IsNullOrEmpty(Request.QueryString["riskid"]))
                {
                    int riskID = 0;
                    int.TryParse(Request.QueryString["riskid"], out riskID);
                    if (riskID > 0) 
                    {
                        strFieldsXml = strFieldsXml.Replace(@"SearchFilterField Name=""AssignedTo"" Default=""True""", @"SearchFilterField Name=""AssignedTo""");
                        strFieldsXml = strFieldsXml.Replace(@"SearchFilterField Name=""Risk""", @"SearchFilterField Name=""Risk"" Default=""True""");
                        
                    }
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(strFieldsXml);
                    XmlNode riskValues = xmlDoc.SelectSingleNode("/SearchFilterFieldsControlData/SearchFilterFields/SearchFilterField[@Name='Risk']/AllowedValues");
                    if (riskValues != null) 
                    {
                        XmlElement allowedValue = xmlDoc.CreateElement("AllowedValue", "");
                        allowedValue.InnerText = riskID.ToString();
                        riskValues.AppendChild(allowedValue);

                    }
                    strFieldsXml = xmlDoc.OuterXml;
                }
                
                ViewState["FieldsXml"] = strFieldsXml;
                
            }
            searchFilterControl1.FieldsXml = strFieldsXml;

            if (Request.QueryString["Load"] == "0")
            {
                searchFilterControl1.SearchFilterLoaded -= searchFitlerControl1_SearchFilterLoaded;
                if (!Page.IsPostBack)
                    chkActiveTasks.Checked = false;
            }

            if (!Page.IsPostBack)
            {
                lblPageHeader.Text = "View Tasks";
                searchFilterControl1.ButtonText = "Search";
            }
        }

        protected void searchFitlerControl1_SearchFilterSelected(object sender, SearchFilterResultEventArgs e) 
        {
            if (e.Result != null)
            {
                ViewState["SortExpression"] = "DueDate";
                ViewState["GridSortDirection"] = true;
                ViewState["SearchFilterResult"] = searchFilterControl1.SelectedFilterResult;
                gridResults.PageIndex = 0;
                this.BindGrid();
            }

        }

        protected void searchFitlerControl1_SearchFilterLoaded(object sender, SearchFilterResultEventArgs e)
        {
            if (e.Result != null)
            {
                ViewState["SortExpression"] = "DueDate";
                ViewState["GridSortDirection"] = true;
                ViewState["SearchFilterResult"]=searchFilterControl1.SelectedFilterResult;
                gridResults.PageIndex = 0;
                this.BindGrid();
            }

        }

        protected void chkActiveTasks_Checked(object sender, EventArgs e)
        {
            gridResults.PageIndex = 0;
            this.BindGrid();
        }
        
        private void BindGrid() 
        {
            gridResults.DataBind();
            if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser")))
            {
                gridResults.Columns[2].Visible = true;
            }
            else
            {
                gridResults.Columns[2].Visible = false;
            }
            lblResults.Text = string.Format("Your query returned {0} result(s).", AntiXss.HtmlEncode(HttpContext.Current.Items["tasksRowCount"].ToString()));
        }

        protected void gridResults_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["GridSortDirection"] != null)
                if ((bool)ViewState["GridSortDirection"] == false)
                    ViewState["GridSortDirection"] = true;
                else
                    ViewState["GridSortDirection"] = false;
            else
                ViewState["GridSortDirection"] = false;
            ViewState["SortExpression"] = e.SortExpression;
            e.Cancel = true;
            this.BindGrid();
        }
        protected void gridResults_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (((Label)e.Row.Cells[4].FindControl("DueDateLabel")).Text != "")
                {
                    DateTime dtDueDate = DateTime.Parse(((Label)e.Row.Cells[4].FindControl("DueDateLabel")).Text);
                    if (dtDueDate < DateTime.Now && ((Label)e.Row.Cells[8].FindControl("StatusLabel")).Text == "Active")
                    {
                        e.Row.Cells[1].FindControl("imgWarning").Visible = true;
                    }
                    
                }
            }
        }

        protected void gridResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridResults.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

        protected void tasksSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (ViewState["SearchFilterResult"] == null)
            {
                e.Cancel = true;
            }

            if (!e.ExecutingSelectCount && ViewState["SearchFilterResult"] != null)
            {
                SearchFilterResult filterResult = (SearchFilterResult)ViewState["SearchFilterResult"];
                if (filterResult.Operator == "Contains")
                    filterResult.Values[0] = "%" + filterResult.Values[0] + "%";

                e.Arguments.MaximumRows = gridResults.PageSize;
                e.Arguments.StartRowIndex = (gridResults.PageIndex * gridResults.PageSize) + 1;
                e.InputParameters.Add("field", filterResult.FieldName);
                e.InputParameters.Add("soperator", filterResult.Operator);
                e.InputParameters.Add("values", filterResult.Values);
                if (ViewState["SortExpression"] == null)
                    e.InputParameters.Add("sortField", "DueDate");
                else
                    e.InputParameters.Add("sortField", ViewState["SortExpression"]);
                e.InputParameters.Add("sortDescending", ViewState["GridSortDirection"]);
                e.InputParameters.Add("isTaskUser", !(this.Context.User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser"))));
                e.InputParameters.Add("personID", ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId);
                if (filterResult.FieldName != "TaskStatus")
                    e.InputParameters.Add("isActiveTasksOnly", chkActiveTasks.Checked);
                else
                    e.InputParameters.Add("isActiveTasksOnly", false);
            }
           
        }

        
        
    }

    public class TaskDataSource
    {
        public TaskDataSource() 
        {
        
        }

        public int SelectCount(string field, string soperator, string[] values, string sortField, bool sortDescending, bool isTaskUser, int personID, bool isActiveTasksOnly)
        {
            return (int)HttpContext.Current.Items["tasksRowCount"];
        }

        public List<Task> Select(string field, string soperator, string[] values, string sortField, bool sortDescending, int maximumRows, int startRowIndex, bool isTaskUser, int personID, bool isActiveTasksOnly)
        {
            List<Task> lstTasks = new List<Task>();
            try
            {
                TasksServiceClient client = new TasksServiceClient();
                int tasksRowCount = client.GetTasksCountByFilter(field, soperator, values, isTaskUser, personID, isActiveTasksOnly);
                if (!HttpContext.Current.Items.Contains("tasksRowCount"))
                    HttpContext.Current.Items.Add("tasksRowCount", tasksRowCount);
                else
                    HttpContext.Current.Items["tasksRowCount"] = tasksRowCount;

                lstTasks.AddRange((Task[])client.GetTasksByFilter(field, soperator, values, sortField, sortDescending, maximumRows, startRowIndex, isTaskUser, personID, isActiveTasksOnly));
                client.Close();
            }
            catch { throw; }
            return lstTasks;
        }
    }

    public class TaskUserComparer : IComparer<User> 
    {

        #region IComparer<User> Members

        public int Compare(User x, User y)
        {
            return StringComparer.CurrentCulture.Compare(x.Name, y.Name);
        }

        #endregion
    }
}
